#!/bin/bash
# Copyright 2021 The Skaffold Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script scans the vulnerability report that is generated by Container Analysis.

set -xeo pipefail
# Variables that will be substituted in cloudbuild.yaml.
if [ -z "$PROJECT_ID" ]; then
  PROJECT_ID=k8s-skaffold
fi
if [ -z "$_IMAGE" ]; then
  _IMAGE="skaffold"
fi
if [ -z "$_TAG_FILTER" ]; then
  _TAG_FILTER="v*lts"
fi
if [ -z "$_SEVERITIES" ]; then
  _SEVERITIES="HIGH CRITICAL"
fi

# If changed, also change the same variable in report.sh.
OS_VULN_FILE=/workspace/os_vuln.txt
BASE_IMAGE="gcr.io/$PROJECT_ID/$_IMAGE"

append() {
  printf "%s\n" $1 >>$2
}

check_vulnerability(){
  base_image=$1
  tags_filter=$2
  severities=$3
  result_file=$4
  tags=$5

  if [ -z "$tags" ]; then
    # Gets the last 5 images if _TAGS is not set.
    tags=$(gcloud container images list-tags "$base_image" --filter="tags~$tags_filter" --limit=5 --format='value(tags)')
  fi
  grep_args=""
  for s in $severities; do
    grep_args="$grep_args -e $s"
  done
  grep_cmd="grep $grep_args"

  for tagsByComma in $tags; do
    IFS="," read -ra tagArr <<< "${tagsByComma}"
    image=$base_image:${tagArr[0]}
    echo "Checking vulnerabilities of image:" $image
    gcloud beta container images describe $image  --show-package-vulnerability \
     | if eval "$grep_cmd"; then append "$base_image":"$tagsByComma" "$result_file"; fi
  done
}

# Main
# Scans the LTS images
check_vulnerability $BASE_IMAGE "$_TAG_FILTER" "$_SEVERITIES" "$OS_VULN_FILE" "$_TAGS"
